package model

import (
	"errors"
	"gorm.io/gorm"
	"time"
)

type (
	ProjectModel interface {
		Insert(project Project) (err error)
		FindOneByProjectId(project Project) (Project, error)
		Update(project Project) (err error)
		DeleteSoft(project Project) (err error)
		Delete(project Project) (err error)
	}

	DefaultProjectModel struct {
		conn  *gorm.DB
		table string
	}

	Project struct {
		Project_id     int       `db:"project_id"  json:"project_id"`
		Project_name   string    `db:"project_name"  json:"project_name"`
		Project_Com_id int       `db:"project_com_id"  json:"project_com_id"`
		Create_time    time.Time `db:"create_time"  json:"create_time"`
		Delete_time    time.Time `db:"delete_time"  json:"delete_time"`
		DelState       int       `db:"del_state"  json:"del_state"`
	}
)

func NewDefaultProjectModel(conn *gorm.DB) *DefaultProjectModel {
	return &DefaultProjectModel{
		conn:  conn,
		table: "project",
	}
}

func (pro *DefaultProjectModel) Insert(project Project) (err error) {
	project.Create_time = time.Now()
	project.Delete_time = time.Unix(0, 0)
	pro.conn.Create(&project)
	return err
}

func (pro *DefaultProjectModel) FindOneByProjectId(project Project) (Project, error) {
	var err error
	var count int64
	pro.conn.Model(&project).Where("project_id=?", project.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return Project{}, err
	}
	pro.conn.Where("project_id=?", project.Project_id).First(&project)

	return project, nil
}

func (pro *DefaultProjectModel) Update(project Project) (err error) {
	var count int64
	pro.conn.Model(&project).Where("project_id=?", project.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	pro.conn.Model(&project).Where("project_id=?", project.Project_id).Updates(&project)
	return nil
}

func (pro *DefaultProjectModel) DeleteSoft(project Project) (err error) {
	project.Delete_time = time.Now()
	project.DelState = 1
	var count int64
	pro.conn.Model(&project).Where("project_id=?", project.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	err = pro.Update(project)
	if err != nil {
		return err
	}
	return nil
}

func (pro *DefaultProjectModel) Delete(project Project) (err error) {
	var count int64
	pro.conn.Model(&project).Where("project_id=?", project.Project_id).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return err
	}
	pro.conn.Model(&project).Where("project_id=?", project.Project_id).Delete(&project)
	return nil
}
